//
//  LoginViewController.m
//  CMVRFForIOS
//
//  Created by 韩海龙 on 15/4/8.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "LoginViewController.h"
#import <TPKeyboardAvoidingTableView.h>
#import "Icon_Input_Cell.h"
#import "LoginDataResp.h"
#import <MBProgressHUD.h>
#import <TTTAttributedLabel.h>

#define USERNAME_PASSWORD_DATA @"userNameAndPasswordData"

typedef NS_ENUM(NSInteger, TTTAttributedLabelType) {
    TTTAttributedLabelTypeNone,
    TTTAttributedLabelTypeUrl,
    TTTAttributedLabelTypePhone
};

@interface LoginViewController ()<UITableViewDataSource,UITableViewDelegate, TTTAttributedLabelDelegate>

@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView;

@property (nonatomic,strong) MBProgressHUD *HUD;

/**
 *  账号（邮箱）
 */
@property (nonatomic,copy) NSString *account;
/**
 *  密码
 */
@property (nonatomic,copy) NSString *password;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //初始化视图
    [self setupViews];
    
    //获取保存的用户名密码信息
    NSDictionary *dicData = [Tools getApplicationData:USERNAME_PASSWORD_DATA];
    if (dicData != nil) {
        LoginDataResp *saveData = [LoginDataResp objectWithKeyValues:dicData];
        self.account = saveData.username;
        self.password = saveData.password;
    }
}

#pragma mark - 初始化视图
- (void)setupViews{
    
    self.tableView = ({
        TPKeyboardAvoidingTableView *tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.backgroundColor = CM_WINDOW_BG_COLOR;
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        self.tableView = tableView;
        tableView;
    });
    
    //添加tableviewHeader
    self.tableView.tableHeaderView = [self addTableViewHeader];
    self.tableView.tableFooterView = [self addTableViewFooter];
    
    UIView *versionView = [self setupVersionView];
    versionView.x = 0;
    versionView.y = kScreen_Height - versionView.height;
    [self.view addSubview:versionView];
    self.tableView.height -= versionView.height;
}

- (UIView *)addTableViewHeader{
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height*2/5)];
    
    //ICON
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Outes"]];
    CGFloat scale = icon.width*2/kScreen_Width;
    icon.width = kScreen_Width/2;
    icon.height = icon.height/scale;
    icon.centerX = headView.centerX;
    icon.centerY = headView.centerY;
    [headView addSubview:icon];
    
    //title
    UILabel *label = [[UILabel alloc] init];
    label.width = 200;
    label.height = 20;
    label.centerX = self.view.width*0.5;
    label.y = CGRectGetMaxY(icon.frame)+10;
    //居中
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = CM_ORANGE_COLOR;
    label.text = kAppName;
//    [headView addSubview:label];
    
    return headView;
}

- (UIView *)addTableViewFooter{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 100)];
    if (iPhone_X) {
        footerView.height += 34;
    }
    
    UIButton *loginBtn = [UIButton buttonWithStyle:StrapSuccessStyle andTitle:@"登录" andFrame:CGRectMake(15, 20, kScreen_Width-30, 45) target:self action:@selector(sendLogin)];
    [loginBtn setTitleColor: [UIColor whiteColor] forState:UIControlStateNormal];
//    [loginBtn setBackgroundColor:CM_ORANGE_COLOR];
    [loginBtn setBackgroundImage:[UIImage imageWithColor:CM_ORANGE_COLOR] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageWithColor:UIColor16Alpha(0xEE6611, 0.5)] forState:UIControlStateDisabled];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    [footerView addSubview:loginBtn];
    
    RAC(loginBtn,enabled) = [RACSignal combineLatest:@[RACObserve(self, account),RACObserve(self, password)] reduce:^id(NSString *account,NSString *pwd){
        return @((account && account.length > 0) && (pwd && pwd.length > 0));
    }];
    
    return footerView;
}

#pragma mark - 执行登录
- (void)sendLogin{
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    self.account = @"欧特斯";
//    self.password = @"135799";
    [params setValue:[self.account base64Encoder] forKey:@"username"];
    [params setValue:[self.password base64Encoder] forKey:@"password"];
    
    [self showLoading];
    
    [HttpClient postWithUrl:HTTP_POST_USER_LOGIN paramDic:params
                resultClass:[LoginDataResp class] success:^(LoginDataResp *obj) {
                    //oc对象归档
                    [self.HUD hide:YES];
                    [[AccountManager manager] logoutAndClearUserInfo];
                    [[AccountManager manager] saveAccount:obj];
                    //保存用户名密码
                    obj.username = self.account;
                    obj.password = self.password;
                    [Tools saveApplicationData:[obj keyValues] forKey:USERNAME_PASSWORD_DATA];
                    
                    [self showMainViewController];
                } failure:^(NSError *error) {
                    [self.HUD hide:YES];
                    [Tools showMessageCenter:@"用户名或密码错误，请重试"];
                    CMLog(@"错误信息为：%@",error);
                }];
    
}

- (void)showLoading{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"用户登录中...";
}


#pragma mark - UITableView代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *IdentifierCell = @"Login_Cell";
    
    Icon_Input_Cell *cell = [tableView dequeueReusableCellWithIdentifier:IdentifierCell];
    
    if (cell == nil) {
        cell = [[Icon_Input_Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:IdentifierCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (indexPath.row == 0) {//账号
        [cell configPlaceHolder:@"请输入你的登录账户" andContent:self.account andIcon:[UIImage imageNamed:@"username"] andIsSecure:NO];
        cell.textValueChangeBlock = ^(NSString *value){
            self.account = value;
        };
        
        cell.editDidEndBlock = ^(NSString *value){
            self.account = value;
        };
        
    }else if (indexPath.row == 1){//密码
        [cell configPlaceHolder:@"请输入登录密码" andContent:self.password andIcon:[UIImage imageNamed:@"password"] andIsSecure:YES];
        cell.textValueChangeBlock = ^(NSString *value){
            self.password = value;
        };
        
        cell.editDidEndBlock = ^(NSString *value){
            self.password = value;
        };
        
    }
    
    return cell;
}

- (UIView *)setupVersionView{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 0)];
    
    NSString *version = [NSString stringWithFormat:@"当前版本号：V%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey]];
    UILabel *label = [UILabel labelSingleLineFontSize:10 content:version];
    label.centerX = self.view.width*0.5;
    label.y = CELL_PADDING_TOP;
    label.textColor = CM_DARKGRAY_COLOR;
    [footerView addSubview:label];
    
    footerView.height = CGRectGetMaxY(label.frame) + 3*CELL_PADDING_BOTTOM;
    
    return footerView;
}

#pragma mark -链接文本处理
/**
 *  填充数据到UILabel
 *
 *  @param label   UILabel
 *  @param title   标题
 *  @param content 内容
 */
- (void)fillDataToLabel:(TTTAttributedLabel *)label content:(NSString *)content url:(NSURL *)url type:(TTTAttributedLabelType)type{
    NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc] initWithString:content];
    [contentStr addAttributes:@{(__bridge NSString *)kCTForegroundColorAttributeName:CM_BLUE_COLOR} range:NSMakeRange(0, contentStr.length)];
    
    label.linkAttributes = kLinkAttributes;
    label.activeLinkAttributes = kLinkAttributesActive;
    label.font = [UIFont boldSystemFontOfSize:13];
    
    label.text = contentStr;
    label.textAlignment = NSTextAlignmentCenter;
    switch (type) {
            case TTTAttributedLabelTypePhone:{
                NSRange range = [label.text rangeOfString:content];
                [label addLinkToPhoneNumber:content withRange:range];
                label.delegate = self;
                break;
            }
            case TTTAttributedLabelTypeUrl:{
                NSRange range = [label.text rangeOfString:content];
                [label addLinkToURL:url withRange:range];
                label.delegate = self;
                break;
            }
        default:
            break;
    }
}

#pragma mark - TTAttributeLabel 代理
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    [[UIApplication sharedApplication] openURL:url];
}

-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithPhoneNumber:(NSString *)phoneNumber{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
}


@end

